<template>
	<div class="mc-popup-select-wrap">
		<div
			class="el-select"
			@click.stop="openDialog"
		>
			<!-- 标签部分，支持多选并显示已选择的标签 -->
			<div
				v-if="multiple"
				ref="tags"
				class="el-select__tags"
				:style="tagsStyle"
			>
				<span v-if="collapseTags && tagsList.length">
					<Tag
						:closable="!selectDisabled"
						:size="collapseTagSize"
						type="info"
						disable-transitions
						@close="deleteTag($event, 0)"
					>
						<span class="el-select__tags-text">{{tagsList[0]}}</span>
					</Tag>
					<Tag
						v-if="tagsList.length > 1"
						:closable="false"
						type="info"
						disable-transitions
					>
						<span class="el-select__tags-text">+ {{tagsList.length - 1}}</span>
					</Tag>
				</span>
				<transition-group
					v-if="!collapseTags"
					@after-leave="resetInputHeight"
				>
					<Tag
						v-for="(item, i) in tagsList"
						:key="item.id"
						:size="collapseTagSize"
						:closable="!selectDisabled"
						type="info"
						disable-transitions
						@close="deleteTag($event, i)"
					>
						<span class="el-select__tags-text">{{item.fullName}}</span>
					</Tag>
				</transition-group>
			</div>
			<!-- 输入框部分 -->
			<Input
				ref="reference"
				v-model="innerValue"
				type="text"
				:placeholder="currentPlaceholder"
				:disabled="selectDisabled"
				readonly
				:validate-event="false"
				:tabindex="multiple ? '-1' : null"
				@mouseenter.native="inputHovering = true"
				@mouseleave.native="inputHovering = false"
			>
				<template #suffix>
					<i
						v-show="!showClose"
						:class="['el-select__caret', 'el-input__icon', 'el-icon-arrow-up']"
					/>
					<i
						v-if="showClose"
						class="el-select__caret el-input__icon el-icon-circle-close"
						@click="handleClearClick"
					/>
				</template>
			</Input>
		</div>
	</div>
</template>

<script>
import {addResizeListener, removeResizeListener} from 'element-ui/src/utils/resize-event';
import {magic} from '@lexmis/magic-ui/pc';
import {Tag, Input} from 'element-ui';
export default {
	name:'McComSelect',
	components:{
		Tag, Input,
	},
	inject:{
		elForm:{default:''},
		elFormItem:{default:''},
	},
	props:{
		value:{type:[Array, String]},
		placeholder:{type:String, default:'请选择'},
		disabled:{type:Boolean, default:false},
		multiple:{type:Boolean, default:false},
		collapseTags:{type:Boolean, default:false},
		clearable:{type:Boolean, default:false},
		auth:{type:Boolean, default:false},
		isOnlyOrg:{type:Boolean, default:false},
		size:String,
		currOrgId:{type:String, default:'0'},
		parentId:{type:String, default:''},
	},
	data(){
		return {
			innerValue:'',
			selectedData:[],
			tagsList:[],
			inputHovering:false,
			inputWidth:0,
			initialInputHeight:0,
		};
	},
	computed:{
		// 控制关闭按钮显示
		showClose(){
			const hasValue = Array.isArray(this.value) && this.value.length > 0;
			return this.clearable && !this.selectDisabled && this.inputHovering && hasValue;
		},
		// 当前的占位符
		currentPlaceholder(){
			return this.multiple && Array.isArray(this.value) && this.value.length ? '' : this.placeholder;
		},
		// 组件是否禁用
		selectDisabled(){
			return this.disabled || (this.elForm || {}).disabled;
		},
		// 获取表单项的大小
		_elFormItemSize(){
			return (this.elFormItem || {}).elFormItemSize;
		},
		// 控制选择框的大小
		selectSize(){
			return this.size || this._elFormItemSize || (this.$ELEMENT || {}).size;
		},
		// 判断标签的大小
		collapseTagSize(){
			return ['small', 'mini'].indexOf(this.selectSize) > -1 ? 'mini' : 'small';
		},
		// 标签样式，动态计算最大宽度
		tagsStyle(){
			return {
				'max-width':this.inputWidth - 32 + 'px',
				width:'100%',
				cursor:'pointer',
			};
		},
	},
	watch:{
		selectDisabled(){
			this.$nextTick(this.resetInputHeight);
		},
	},
	mounted(){
		addResizeListener(this.$el, this.handleResize);
		this.initializeInputDimensions();
		this.setDefaultValue();
	},
	beforeUnmount(){
		if(this.$el && this.handleResize) removeResizeListener(this.$el, this.handleResize);
	},
	methods:{
		// 设置默认值
		setDefaultValue(){
			if(!this.value || !this.value.length){
				this.resetSelection();
				return;
			}
			const orgIds = Array.isArray(this.value) ? this.value : [this.value];
			magic.core
				.service({
					url:'/api/magic-org/getOrgByIds',
					method:'post',
					data:{orgIds},
				})
				.then(({data}) => {
					this.selectedData = data;
					this.handleTagsUpdate(data);
				});
		},
		// 重置选择项
		resetSelection(){
			this.innerValue = '';
			this.selectedData = [];
			this.tagsList = [];
			this.$nextTick(this.resetInputHeight);
		},
		// 处理标签更新
		handleTagsUpdate(data){
			if(this.multiple){
				this.innerValue = '';
				this.tagsList = data.map((item) => ({id:item.id, fullName:item.fullName || item.orgName}));
			}else{
				this.innerValue = data.length ? data[0].fullName : '';
			}
			this.$nextTick(this.resetInputHeight);
		},
		// 打开选择框(选择组织)
		openDialog(){
			magic.base.selectPeople({
				selectType:['Post'],
				min:0,
				max:this.multiple ? -1 : 1,
				fillBackData:this.value ? Array.isArray(this.value) ? this.value : [this.value] : [],
			}).then((data) => {
				this.selectedData = data;
				this.handleTagsUpdate(data);
				this.emitValueChange(data);
			});
		},
		// 处理选中值变化
		emitValueChange(data){
			if(this.multiple){
				const selectedIds = data.map((item) => item.id);
				this.$emit('input', selectedIds);
				this.$emit('change', selectedIds, this.tagsList);
			}else{
				this.innerValue = data[0] ? data[0].name || data[0].fullName : '';
				this.$emit('input', data[0]?.id || '');
				this.$emit('change', data[0]?.id || '', data[0] || {});
			}
		},
		// 删除标签
		deleteTag(event, index){
			this.selectedData.splice(index, 1);
			this.tagsList.splice(index, 1);
			this.$emit('input', this.selectedData.map((item) => item.id));
			event.stopPropagation();
		},
		// 清除选择项
		handleClearClick(event){
			this.selectedData = [];
			event.stopPropagation();
		},
		// 重置输入框宽度
		resetInputWidth(){
			this.$nextTick(() => {
				if(this.$refs.reference && this.$refs.reference.$el){
					this.inputWidth = this.$refs.reference.$el.getBoundingClientRect().width;
				}
			});
		},
		// 处理窗口尺寸变化
		handleResize(){
			this.resetInputWidth();
			if(this.multiple)this.resetInputHeight();
		},
		// 初始化输入框尺寸
		initializeInputDimensions(){
			const reference = this.$refs.reference;
			if(reference && reference.$el){
				const sizeMap = {medium:36, small:32, mini:28};
				const input = reference.$el.querySelector('input');
				this.initialInputHeight = input.getBoundingClientRect().height || sizeMap[this.selectSize];
			}
			if(this.multiple){
				this.resetInputWidth();
			}
		},
		// 重置输入框高度
		resetInputHeight(){
			if(this.$refs.reference){
				const input = this.$refs.reference.$el.querySelector('input');
				if(input) input.style.height = this.initialInputHeight + 'px';
			}
		},
	},
};
</script>